<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检疫类型" prop="quaType">
        <el-select v-model="queryParams.quaType" placeholder="请选择检疫类型" clearable>
          <el-option
            v-for="dict in dict.type.qua_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检疫项目名称" prop="quaItemName" label-width="20">
        <el-input
          v-model="queryParams.quaItemName"
          placeholder="请输入检疫项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检疫项目类型" prop="quaItemType" label-width="20">
        <el-select v-model="queryParams.quaItemType" placeholder="请选择检疫项目类型" clearable>
          <el-option
            v-for="dict in dict.type.qua_item_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="定性结果" prop="quaResult">
        <el-select v-model="queryParams.quaResult" placeholder="请选择定性结果" clearable>
          <el-option
            v-for="dict in dict.type.qua_result"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="最大值" prop="standardMax">
        <el-input
          v-model="queryParams.standardMax"
          placeholder="请输入最大值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最小值" prop="standardMin">
        <el-input
          v-model="queryParams.standardMin"
          placeholder="请输入最小值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否关键项目" prop="isKeyItem" label-width="20">
        <el-select v-model="queryParams.isKeyItem" placeholder="请选择是否关键项目" clearable>
          <el-option
            v-for="dict in dict.type.is_key_item"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleInitiateQuarantine"
            v-hasPermi="['animalManagement:quaItem:initiate']"
        >发起检疫</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleInputQuarantine"
            v-hasPermi="['animalManagement:quaItem:input']"
        >检疫录入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="handleEliminate"
            v-hasPermi="['animalManagement:quaItem:eliminate']"
        >动物淘汰</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-location"
            size="mini"
            @click="handleAssignCage"
            v-hasPermi="['animalManagement:quaItem:assign']"
        >分配笼位</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['animalManagement:quaItem:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['animalManagement:quaItem:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['animalManagement:quaItem:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['animalManagement:quaItem:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="quaItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检疫项目编码" align="center" prop="quaItemId" />
      <el-table-column label="检疫类型" align="center" prop="quaType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qua_type" :value="scope.row.quaType"/>
        </template>
      </el-table-column>
      <el-table-column label="检疫项目名称" align="center" prop="quaItemName" />
      <el-table-column label="检疫项目类型" align="center" prop="quaItemType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qua_item_type" :value="scope.row.quaItemType"/>
        </template>
      </el-table-column>
      <el-table-column label="定性结果" align="center" prop="quaResult">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.qua_result" :value="scope.row.quaResult"/>
        </template>
      </el-table-column>
      <el-table-column label="最大值" align="center" prop="standardMax" />
      <el-table-column label="最小值" align="center" prop="standardMin" />
      <el-table-column label="是否关键项目" align="center" prop="isKeyItem">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_key_item" :value="scope.row.isKeyItem"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['animalManagement:quaItem:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['animalManagement:quaItem:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改检疫项目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-col :span="12">
            <el-form-item label="检疫类型" prop="quaType">
              <el-select v-model="form.quaType" placeholder="请选择检疫类型">
                <el-option
                  v-for="dict in dict.type.qua_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="检疫项目名称" prop="quaItemName">
              <el-input v-model="form.quaItemName" placeholder="请输入检疫项目名称" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="检疫项目类型" prop="quaItemType">
              <el-select v-model="form.quaItemType" placeholder="请选择检疫项目类型" @change="handleQuaItemTypeChange">
                <el-option
                  v-for="dict in dict.type.qua_item_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.quaItemType === '1'">
            <el-form-item label="定性结果" prop="quaResult">
              <el-select v-model="form.quaResult" placeholder="请选择定性结果">
                <el-option
                  v-for="dict in dict.type.qua_result"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.quaItemType === '2'">
            <el-form-item label="最大值" prop="standardMax">
              <el-input v-model="form.standardMax" placeholder="请输入最大值" type="number" />
            </el-form-item>
        </el-col>
        <el-col :span="12" v-if="form.quaItemType === '2'">
            <el-form-item label="最小值" prop="standardMin">
              <el-input v-model="form.standardMin" placeholder="请输入最小值" type="number" />
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="是否关键项目" prop="isKeyItem">
              <el-select v-model="form.isKeyItem" placeholder="请选择是否关键项目">
                <el-option
                  v-for="dict in dict.type.is_key_item"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
        </el-col>
<!--        <el-divider content-position="center">检疫纪录信息</el-divider>-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddLmisQuaRecord">添加</el-button>-->
<!--          </el-col>-->
<!--          <el-col :span="1.5">-->
<!--            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteLmisQuaRecord">删除</el-button>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--        <el-table :data="lmisQuaRecordList" :row-class-name="rowLmisQuaRecordIndex" @selection-change="handleLmisQuaRecordSelectionChange" ref="lmisQuaRecord">-->
<!--          <el-table-column type="selection" width="50" align="center" />-->
<!--          <el-table-column label="序号" align="center" prop="index" width="50"/>-->
<!--          <el-table-column label="动物编码" prop="animalId" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.animalId" placeholder="请选择动物编码">-->
<!--                <el-option label="请选择字典生成" value="" />-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="检疫类型" prop="quaType" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.quaType" placeholder="请选择检疫类型">-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.qua_type"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="检疫时间" prop="quaTime" width="240">-->
<!--            <template slot-scope="scope">-->
<!--              <el-date-picker clearable v-model="scope.row.quaTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择检疫时间" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="检疫人员" prop="userName" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.userName" placeholder="请选择检疫人员">-->
<!--                <el-option label="请选择字典生成" value="" />-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="检疫结果" prop="overallResult" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.overallResult" placeholder="请选择检疫结果">-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.overall_result"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="处理方式" prop="handleMethod" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-select v-model="scope.row.handleMethod" placeholder="请选择处理方式">-->
<!--                <el-option-->
<!--                  v-for="dict in dict.type.handle_method"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                ></el-option>-->
<!--              </el-select>-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--          <el-table-column label="笼位位置" prop="position" width="150">-->
<!--            <template slot-scope="scope">-->
<!--              <el-input v-model="scope.row.position" placeholder="请输入笼位位置" />-->
<!--            </template>-->
<!--          </el-table-column>-->
<!--        </el-table>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 发起检疫对话框 -->
    <el-dialog title="发起检疫" :visible.sync="initiateDialog" width="1200px" append-to-body>
      <el-tabs v-model="activeTab" type="border-card" @tab-click="onInitiateTabClick">
        <!-- 第一个页签：动物档案列表 -->
        <el-tab-pane label="选择动物" name="animals">
          <el-form :model="animalQueryParams" ref="animalQueryForm" size="small" :inline="true" label-width="80px">
            <el-form-item label="动物编码" prop="animalCode">
              <el-input v-model="animalQueryParams.animalCode" placeholder="请输入动物编码" clearable />
            </el-form-item>
            <el-form-item label="动物名称" prop="animalName">
              <el-input v-model="animalQueryParams.animalName" placeholder="请输入动物名称" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAnimalQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetAnimalQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="animalList" @selection-change="handleAnimalSelectionChange" height="300">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="动物编码" align="center" prop="animalId" />
            <el-table-column label="动物名称" align="center" prop="animalName" />
            <el-table-column label="动物类型" align="center" prop="animalType" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.animal_type" :value="scope.row.animalType"/>
              </template>
            </el-table-column>
            <el-table-column label="性别" align="center" prop="gender">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.gender" :value="scope.row.gender"/>
              </template>
            </el-table-column>
            <el-table-column label="年龄" align="center" prop="age" />
            <el-table-column label="状态" align="center" prop="animalStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.animal_status" :value="scope.row.animalStatus"/>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="animalTotal>0"
            :total="animalTotal"
            :page.sync="animalQueryParams.pageNum"
            :limit.sync="animalQueryParams.pageSize"
            @pagination="getAnimalList"
          />
        </el-tab-pane>

        <!-- 第二个页签：检疫信息 -->
        <el-tab-pane label="检疫信息" name="quarantine">
          <el-form :model="quarantineForm" ref="quarantineForm" :rules="quarantineRules" label-width="120px" :inline="true">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检疫类型" prop="quaType">
                  <el-select v-model="quarantineForm.quaType" placeholder="请选择检疫类型" @change="handleQuaTypeChange">
                    <el-option
                      v-for="dict in dict.type.qua_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检疫时间" prop="quaTime">
                  <el-date-picker
                    v-model="quarantineForm.quaTime"
                    type="datetime"
                    placeholder="选择检疫时间"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检疫人员" prop="userName">
                  <el-select v-model="quarantineForm.userName" placeholder="请选择检疫人员" filterable>
                    <el-option
                      v-for="user in userList"
                      :key="user.userId"
                      :label="user.userName"
                      :value="user.userId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 检疫项目列表 -->
            <el-divider content-position="left">检疫项目</el-divider>
            <el-table :data="quarantineItems" border>
              <el-table-column label="项目名称" align="center" prop="quaItemName" />
              <el-table-column label="项目类型" align="center" prop="quaItemType">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.qua_item_type" :value="scope.row.quaItemType"/>
                </template>
              </el-table-column>
              <el-table-column label="是否关键项目" align="center" prop="isKeyItem">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.is_key_item" :value="scope.row.isKeyItem"/>
                </template>
              </el-table-column>
              <el-table-column label="标准值" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.quaItemType === '1'">
                    {{ scope.row.quaResult === '1' ? '阴性' : '阳性' }}
                  </span>
                  <span v-else>
                    {{ scope.row.standardMin }} - {{ scope.row.standardMax }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitInitiateQuarantine">确认发起</el-button>
        <el-button @click="initiateDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 检疫录入对话框 -->
    <el-dialog title="检疫录入" :visible.sync="inputDialog" width="1200px" append-to-body :before-close="onCloseInputDialog">
      <!-- 检疫记录选择 -->
      <el-form :model="inputQueryParams" ref="inputQueryForm" size="small" :inline="true" label-width="100px" style="margin-bottom: 20px;">
        <el-form-item label="检疫类型" prop="quaType">
          <el-select v-model="inputQueryParams.quaType" placeholder="请选择检疫类型" clearable>
            <el-option
              v-for="dict in dict.type.qua_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检疫状态" prop="quaStatus">
          <el-select v-model="inputQueryParams.quaStatus" placeholder="请选择检疫状态" clearable>
            <el-option label="已发起" value="1" />
            <el-option label="已检疫" value="2" />
            <el-option label="已完成" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleInputQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetInputQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 检疫记录列表 -->
      <el-table :data="quaRecordList" @selection-change="handleQuaRecordSelectionChange" height="300">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="检疫记录ID" align="center" prop="quaRecordId" />
        <el-table-column label="动物编码" align="center" prop="animalId" />
        <el-table-column label="检疫类型" align="center" prop="quaType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.qua_type" :value="scope.row.quaType"/>
          </template>
        </el-table-column>
        <el-table-column label="检疫时间" align="center" prop="quaTime" />
        <el-table-column label="检疫人员" align="center" prop="userName" />
        <el-table-column label="检疫状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.overallResult == null ? 'warning' : 'success'">
              {{ scope.row.overallResult == null ? '已发起' : '已检疫' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="quaRecordTotal>0"
        :total="quaRecordTotal"
        :page.sync="inputQueryParams.pageNum"
        :limit.sync="inputQueryParams.pageSize"
        @pagination="getQuaRecordList"
      />

      <el-divider content-position="left">检疫项目录入</el-divider>
      <el-form :model="inputForm" ref="inputForm" :rules="inputRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="检疫类型" prop="quaType">
              <el-input v-model="inputForm.quaType" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检疫时间" prop="quaTime">
              <el-input v-model="inputForm.quaTime" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检疫人员" prop="userName">
              <el-input v-model="inputForm.userName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 检疫项目录入 -->
        <el-table :data="inputForm.quaItems" border>
          <el-table-column label="项目名称" align="center" prop="quaItemName" />
          <el-table-column label="项目类型" align="center" prop="quaItemType">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.qua_item_type" :value="scope.row.quaItemType"/>
            </template>
          </el-table-column>
          <el-table-column label="标准值" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.quaItemType === '1'">
                {{ scope.row.quaResult === '1' ? '阴性' : '阳性' }}
              </span>
              <span v-else>
                {{ scope.row.standardMin }} - {{ scope.row.standardMax }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="检测结果" align="center" width="200">
            <template slot-scope="scope">
              <el-select
                v-if="scope.row.quaItemType === '1'"
                v-model="scope.row.testResult"
                placeholder="请选择检测结果"
                @change="validateResult(scope.row)"
                style="width: 100%"
              >
                <el-option label="阴性" value="1" />
                <el-option label="阳性" value="0" />
              </el-select>
              <el-input-number
                v-else
                v-model="scope.row.testResult"
                :min="0"
                :precision="2"
                placeholder="请输入检测结果"
                @change="validateResult(scope.row)"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="是否合格" align="center" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isQualified ? 'success' : 'danger'">
                {{ scope.row.isQualified ? '合格' : '不合格' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="附件" align="center" width="150">
            <template slot-scope="scope">
              <el-upload
                :action="uploadUrl"
                :file-list="scope.row.fileList"
                :on-success="(response, file, fileList) => handleFileSuccess(response, file, fileList, scope.row)"
                :on-remove="(file, fileList) => handleFileRemove(file, fileList, scope.row)"
                multiple
                :limit="5"
              >
                <el-button size="mini" type="primary">上传</el-button>
              </el-upload>
            </template>
          </el-table-column>
        </el-table>

        <el-row :gutter="20" style="margin-top: 20px;">
          <el-col :span="12">
            <el-form-item label="整体结果" prop="overallResult">
              <el-select v-model="inputForm.overallResult" placeholder="请选择整体结果">
                <el-option label="通过" value="1" />
                <el-option label="未通过" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="inputForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="!inputHasChanges" @click="submitInputQuarantine">确认提交</el-button>
        <el-button @click="cancelInputDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 动物淘汰确认对话框 -->
    <el-dialog title="动物淘汰确认" :visible.sync="eliminateDialog" width="500px" append-to-body>
      <div style="text-align: center; padding: 20px;">
        <i class="el-icon-warning" style="font-size: 48px; color: #E6A23C; margin-bottom: 20px;"></i>
        <p style="font-size: 16px; margin-bottom: 10px;">确认要淘汰选中的动物吗？</p>
        <p style="color: #909399; font-size: 14px;">淘汰后动物状态将变更为"淘汰"，此操作不可逆。</p>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="danger" @click="confirmEliminate">确认淘汰</el-button>
        <el-button @click="eliminateDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择动物对话框（用于动物淘汰/分配笼位） -->
    <el-dialog :title="currentAction === 'eliminate' ? '选择动物（可多选）' : '选择动物（单选）'" :visible.sync="animalSelectDialog" width="1000px" append-to-body>
      <el-form :model="animalSelectQueryParams" ref="animalSelectQueryForm" size="small" :inline="true" label-width="80px">
        <el-form-item label="动物编码" prop="animalCode">
          <el-input v-model="animalSelectQueryParams.animalCode" placeholder="请输入动物编码" clearable />
        </el-form-item>
        <el-form-item label="动物名称" prop="animalName">
          <el-input v-model="animalSelectQueryParams.animalName" placeholder="请输入动物名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAnimalSelectQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetAnimalSelectQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-alert v-if="currentAction === 'assign'" type="info" :closable="false" title="分配笼位暂仅支持单选，请选择一条动物记录" style="margin-bottom: 10px;" />

      <el-table :data="animalSelectList" @selection-change="handleAnimalSelectChange" height="300">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="动物编码" align="center" prop="animalId" />
        <el-table-column label="动物名称" align="center" prop="animalName" />
        <el-table-column label="动物类型" align="center" prop="animalType" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.animal_type" :value="scope.row.animalType"/>
          </template>
        </el-table-column>
        <el-table-column label="性别" align="center" prop="gender" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.gender" :value="scope.row.gender"/>
          </template>
        </el-table-column>
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="状态" align="center" prop="animalStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.animal_status" :value="scope.row.animalStatus"/>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="animalSelectTotal>0"
        :total="animalSelectTotal"
        :page.sync="animalSelectQueryParams.pageNum"
        :limit.sync="animalSelectQueryParams.pageSize"
        @pagination="getAnimalSelectList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmAnimalSelect">确认</el-button>
        <el-button @click="animalSelectDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配笼位对话框 -->
    <el-dialog title="分配笼位" :visible.sync="assignCageDialog" width="800px" append-to-body>
      <el-form :model="cageForm" ref="cageForm" :rules="cageRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="动物编码" prop="animalCode">
              <el-input v-model="cageForm.animalCode" disabled />
            </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="动物名称" prop="animalName">
                <el-input v-model="cageForm.animalName" disabled />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="笼位编号" prop="cageId">
                <el-select v-model="cageForm.cageId" placeholder="请选择笼位" filterable>
                  <el-option
                    v-for="cage in availableCages"
                    :key="cage.cageId"
                    :label="cage.cageCode + ' - ' + cage.cageName"
                    :value="cage.cageId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="笼位位置" prop="position">
                <el-input v-model="cageForm.position" placeholder="请输入具体位置描述" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="cageForm.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="confirmAssignCage">确认分配</el-button>
          <el-button @click="assignCageDialog = false">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listQuaItem, getQuaItem, delQuaItem, addQuaItem, updateQuaItem, getQuaItemsByType, initiateQuarantine, inputQuarantine, eliminateAnimal, assignCage, listQuaRecord, getQuaRecord, listQuaRecordItem } from "@/api/animalManagement/quaItem";
import { listAnimal, updateAnimal } from "@/api/animalManagement/animal";
import { listCage, getUser } from "@/api/animalManagement/cage";

export default {
  name: "QuaItem",
  dicts: ['qua_item_type', 'overall_result', 'handle_method', 'qua_type', 'is_key_item', 'qua_result', 'animal_status','gender','animal_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedLmisQuaRecord: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检疫项目表格数据
      quaItemList: [],
      // 检疫纪录表格数据
      lmisQuaRecordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        quaType: null,
        quaItemName: null,
        quaItemType: null,
        quaResult: null,
        standardMax: null,
        standardMin: null,
        isKeyItem: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        quaType: [
          { required: true, message: "检疫类型不能为空", trigger: "change" }
        ],
        quaItemName: [
          { required: true, message: "检疫项目名称不能为空", trigger: "blur" }
        ],
        quaItemType: [
          { required: true, message: "检疫项目类型不能为空", trigger: "change" }
        ],
        quaResult: [
          { 
            required: true, 
            message: "定性结果不能为空", 
            trigger: "change",
            validator: (rule, value, callback) => {
              if (this.form.quaItemType === '1' && !value) {
                callback(new Error('定性结果不能为空'));
              } else {
                callback();
              }
            }
          }
        ],
        standardMax: [
          { 
            required: true, 
            message: "最大值不能为空", 
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.form.quaItemType === '2' && !value) {
                callback(new Error('最大值不能为空'));
              } else if (this.form.quaItemType === '2' && this.form.standardMin && parseFloat(value) <= parseFloat(this.form.standardMin)) {
                callback(new Error('最大值必须大于最小值'));
              } else {
                callback();
              }
            }
          }
        ],
        standardMin: [
          { 
            required: true, 
            message: "最小值不能为空", 
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (this.form.quaItemType === '2' && !value) {
                callback(new Error('最小值不能为空'));
              } else if (this.form.quaItemType === '2' && this.form.standardMax && parseFloat(value) >= parseFloat(this.form.standardMax)) {
                callback(new Error('最小值必须小于最大值'));
              } else {
                callback();
              }
            }
          }
        ],
      },
      // 发起检疫相关
      initiateDialog: false,
      activeTab: 'animals', // 当前激活的tab
      animalQueryParams: {
        pageNum: 1,
        pageSize: 10,
        animalCode: null,
        animalName: null,
      },
      // 检疫信息的查询模型（与筛选一致，这里直接复用 quarantineForm 的三个字段）
      animalList: [],
      animalTotal: 0,
      quarantineForm: {
        quaType: null,
        quaTime: null,
        userName: null,
        quaItems: [],
      },
      quarantineRules: {
        // quaType: [{ required: true, message: '检疫类型不能为空', trigger: 'change' }],
      },
      quarantineItems: [],
      userList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',
      // 检疫录入相关
      inputDialog: false,
      inputForm: {
        quaType: null,
        quaTime: null,
        userName: null,
        quaRecordId: null,
        quaItems: [],
        overallResult: null,
        remark: null,
      },
      // 录入时的原始快照，用于脏数据对比
      inputOriginalMap: {}, // key: quaItemId -> { testResult, isQualified }
      inputRules: {
        overallResult: [{ required: true, message: '整体结果不能为空', trigger: 'change' }],
      },
      inputHasChanges: false,
      // 动物淘汰相关
      eliminateDialog: false,
      // 分配笼位相关
      assignCageDialog: false,
      cageForm: {
        animalCode: null,
        animalName: null,
        cageId: null,
        position: null,
        remark: null,
      },
      cageRules: {
        cageId: [{ required: true, message: '笼位不能为空', trigger: 'change' }],
        position: [{ required: true, message: '笼位位置不能为空', trigger: 'blur' }],
      },
      availableCages: [],
      // 选择动物对话框（用于淘汰/分配）
      animalSelectDialog: false,
      currentAction: null, // 'eliminate' | 'assign'
      animalSelectQueryParams: {
        pageNum: 1,
        pageSize: 10,
        animalCode: null,
        animalName: null,
      },
      animalSelectList: [],
      animalSelectTotal: 0,
      selectedAnimalIds: [],
      // 检疫记录选择相关
      inputQueryParams: {
        pageNum: 1,
        pageSize: 10,
        quaType: null,
        quaStatus: null,
      },
      quaRecordList: [],
      quaRecordTotal: 0,
    };
  },
  created() {
    this.getList();
    this.getUserList();
  },
  methods: {
    /** 查询检疫项目列表 */
    getList() {
      this.loading = true;
      listQuaItem(this.queryParams).then(response => {
        this.quaItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取用户列表 */
    getUserList() {
      getUser().then(response => {
        this.userList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        quaItemId: null,
        quaType: null,
        quaItemName: null,
        quaItemType: null,
        quaResult: null,
        standardMax: null,
        standardMin: null,
        isKeyItem: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.lmisQuaRecordList = [];
      this.resetForm("form");
      // 清除表单验证错误
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.quaItemId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检疫项目";
    },
    /** 处理检疫项目类型变化 */
    handleQuaItemTypeChange() {
      // 当项目类型改变时，清空相关字段
      if (this.form.quaItemType === '1') {
        // 定性类型：清空最大值和最小值
        this.form.standardMax = null;
        this.form.standardMin = null;
      } else if (this.form.quaItemType === '2') {
        // 定量类型：清空定性结果
        this.form.quaResult = null;
      }
      
      // 清除相关字段的验证错误
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate(['quaResult', 'standardMax', 'standardMin']);
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const quaItemId = row.quaItemId || this.ids
      getQuaItem(quaItemId).then(response => {
        this.form = response.data;
        this.lmisQuaRecordList = response.data.lmisQuaRecordList;
        this.open = true;
        this.title = "修改检疫项目";
        // 清除表单验证错误
        this.$nextTick(() => {
          this.$refs.form && this.$refs.form.clearValidate();
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.lmisQuaRecordList = this.lmisQuaRecordList;
          if (this.form.quaItemId != null) {
            updateQuaItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addQuaItem(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const quaItemIds = row.quaItemId || this.ids;
      this.$modal.confirm('是否确认删除检疫项目编号为"' + quaItemIds + '"的数据项？').then(function() {
        return delQuaItem(quaItemIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 检疫纪录序号 */
    rowLmisQuaRecordIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 检疫纪录添加按钮操作 */
    handleAddLmisQuaRecord() {
      let obj = {};
      obj.animalId = "";
      obj.quaType = "";
      obj.quaTime = "";
      obj.userName = "";
      obj.overallResult = "";
      obj.handleMethod = "";
      obj.position = "";
      obj.attachment = "";
      this.lmisQuaRecordList.push(obj);
    },
    /** 检疫纪录删除按钮操作 */
    handleDeleteLmisQuaRecord() {
      if (this.checkedLmisQuaRecord.length == 0) {
        this.$modal.msgError("请先选择要删除的检疫纪录数据");
      } else {
        const lmisQuaRecordList = this.lmisQuaRecordList;
        const checkedLmisQuaRecord = this.checkedLmisQuaRecord;
        this.lmisQuaRecordList = lmisQuaRecordList.filter(function(item) {
          return checkedLmisQuaRecord.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleLmisQuaRecordSelectionChange(selection) {
      this.checkedLmisQuaRecord = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('animalManagement/quaItem/export', {
        ...this.queryParams
      }, `quaItem_${new Date().getTime()}.xlsx`)
    },
    // 发起检疫相关
    handleInitiateQuarantine() {
      this.initiateDialog = true;
      this.activeTab = 'animals';
      this.animalList = [];
      this.animalTotal = 0;
      this.quarantineForm = {
        quaType: null,
        quaTime: null,
        userName: null,
        quaItems: [],
      };
      this.quarantineItems = [];
      // 用户列表已在created生命周期中加载，无需重复加载
      // 自动加载动物列表数据，无需手动搜索
      this.$nextTick(() => {
        this.getAnimalList();
      });
    },
    handleAnimalQuery() {
      this.animalQueryParams.pageNum = 1;
      this.getAnimalList();
    },
    resetAnimalQuery() {
      this.resetForm("animalQueryForm");
      this.handleAnimalQuery();
    },
    getAnimalList() {
      this.loading = true;
      listAnimal(this.animalQueryParams).then(response => {
        this.animalList = response.rows;
        this.animalTotal = response.total;
        this.loading = false;
      });
    },
    handleAnimalSelectionChange(selection) {
      this.quarantineForm.quaItems = selection.map(item => ({
        ...item,
        testResult: null,
        isQualified: null,
        fileList: [],
      }));
      // 自动查询：切到检疫信息页时或当前在检疫信息页，若类型已选则加载项目
      if (this.activeTab === 'quarantine' && this.quarantineForm.quaType) {
        this.getQuarantineItems();
      }
    },
    handleQuaTypeChange() {
      this.quarantineItems = [];
      if (this.quarantineForm.quaType) {
        this.$nextTick(() => {
          this.getQuarantineItems();
        });
      }
    },
    onInitiateTabClick(tab) {
      if (tab.name === 'quarantine' && this.quarantineForm.quaType) {
        this.getQuarantineItems();
      }
    },
    handleQuarantineQuery() {
      if (!this.quarantineForm.quaType) {
        // this.$modal.msgWarning('请先选择检疫类型');
        return;
      }
      this.getQuarantineItems();
    },
    resetQuarantineQuery() {
      this.quarantineForm.quaType = null;
      this.quarantineForm.quaTime = null;
      this.quarantineForm.userName = null;
      this.quarantineItems = [];
    },
    getQuarantineItems() {
      this.loading = true;
      getQuaItemsByType(this.quarantineForm.quaType).then(response => {
        this.quarantineItems = response.data;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.quarantineItems = [];
      });
    },
    submitInitiateQuarantine() {
      this.$refs["quarantineForm"].validate(valid => {
        if (valid) {
          if (this.quarantineForm.quaItems.length === 0) {
            this.$modal.msgError("请选择要检疫的动物");
            return;
          }

          if (this.quarantineItems.length === 0) {
            this.$modal.msgError("请选择检疫类型以获取检疫项目");
            return;
          }

          const data = {
            animals: this.quarantineForm.quaItems,
            quaType: this.quarantineForm.quaType,
            quaTime: this.quarantineForm.quaTime,
            userName: this.quarantineForm.userName,
            quaItems: this.quarantineItems,
            quaStatus: '1' // 检疫流程状态为"已发起"
          };

          initiateQuarantine(data).then(response => {
            this.$modal.msgSuccess("发起检疫成功");
            this.initiateDialog = false;
            this.getList();
          }).catch(() => {
            this.$modal.msgError("发起检疫失败");
          });
        }
      });
    },
    // 检疫录入相关
    handleInputQuarantine() {
      this.inputDialog = true;
      this.inputForm.quaItems = [];
      this.inputForm.overallResult = null;
      this.inputForm.remark = null;
      this.inputQueryParams.pageNum = 1; // 重置分页
      this.quaRecordList = []; // 清空检疫记录列表
      this.quaRecordTotal = 0; // 重置总条数
      this.getQuaRecordList(); // 获取检疫记录列表
    },
    handleInputQuery() {
      this.inputQueryParams.pageNum = 1;
      this.getQuaRecordList();
    },
    resetInputQuery() {
      this.resetForm("inputQueryForm");
      this.handleInputQuery();
    },
    getQuaRecordList() {
      this.loading = true;
      listQuaRecord(this.inputQueryParams).then(response => {
        this.quaRecordList = response.rows;
        this.quaRecordTotal = response.total;
        this.loading = false;
      });
    },
    handleQuaRecordSelectionChange(selection) {
      if (selection.length === 0) {
        this.inputForm.quaItems = [];
        this.inputForm.quaRecordId = null;
        return;
      }
      // 当前仅允许单选
      const selectedRecord = selection[0];
      this.inputForm.quaRecordId = selectedRecord.quaRecordId;
      this.inputForm.quaType = selectedRecord.quaType;
      this.inputForm.quaTime = selectedRecord.quaTime;
      this.inputForm.userName = selectedRecord.userName;
      this.loadRecordItems(selectedRecord.quaRecordId, selectedRecord.quaType);
    },
    loadRecordItems(quaRecordId, quaType) {
      this.loading = true;
      Promise.all([
        getQuaItemsByType(quaType),
        listQuaRecordItem({ quaRecordId })
      ]).then(([itemsResp, detailResp]) => {
        const items = itemsResp.data || [];
        const details = detailResp.data || [];
        const detailMap = {};
        details.forEach(d => {
          detailMap[d.quaItemId] = d;
        });
        this.inputForm.quaItems = items.map(item => {
          const d = detailMap[item.quaItemId] || {};
          const row = {
            ...item,
            testResult: d.testResult || null,
            isQualified: d.isQualified === 1,
            fileList: [],
            _baseResult: d.testResult || null,
            _baseQualified: d.isQualified === 1
          };
          return row;
        });
        // 建立原始快照映射
        this.inputOriginalMap = this.inputForm.quaItems.reduce((acc, r) => {
          acc[r.quaItemId] = { testResult: r._baseResult, isQualified: r._baseQualified };
          return acc;
        }, {});
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.inputForm.quaItems = [];
      });
    },
    submitInputQuarantine() {
      this.$refs["inputForm"].validate(valid => {
        if (valid) {
          if (this.inputForm.quaItems.length === 0) {
            this.$modal.msgError("请选择检疫记录");
            return;
          }

          // 检查是否所有项目都已录入结果
          const uncompletedItems = this.inputForm.quaItems.filter(item =>
            item.testResult === null || item.testResult === ''
          );

          if (uncompletedItems.length > 0) {
            this.$modal.msgError("请完成所有检疫项目的录入");
            return;
          }

          // 仅提交有变更的项目
          const changedItems = this.inputForm.quaItems.filter(r => {
            const base = this.inputOriginalMap[r.quaItemId] || { testResult: null, isQualified: null };
            return String(r.testResult ?? '') !== String(base.testResult ?? '') || Boolean(r.isQualified) !== Boolean(base.isQualified);
          }).map(r => ({
            quaItemId: r.quaItemId,
            testResult: r.testResult,
            isQualified: r.isQualified
          }));

          if (changedItems.length === 0) {
            this.$modal.msgWarning('没有需要保存的变更');
            return;
          }

          const data = {
            quaRecordId: this.inputForm.quaRecordId,
            quaItems: changedItems,
            overallResult: this.inputForm.overallResult,
            remark: this.inputForm.remark,
            quaStatus: '2' // 检疫流程状态为"已检疫"
          };

          inputQuarantine(data).then(response => {
            this.$modal.msgSuccess("检疫录入成功");
            this.inputDialog = false;
            this.getList();
          }).catch(() => {
            this.$modal.msgError("检疫录入失败");
          });
        }
      });
    },
    validateResult(item) {
      if (item.quaItemType === '1') {
        // 定性类型：阴性为合格
        item.isQualified = item.testResult === '1';
      } else {
        // 定量类型：与最大值最小值比较
        item.isQualified = item.testResult >= item.standardMin && item.testResult <= item.standardMax;
      }

      // 自动判断整体结果
      this.autoJudgeOverallResult();
      this.updateInputHasChanges();
    },
    autoJudgeOverallResult() {
      if (this.inputForm.quaItems.length === 0) {
        return;
      }

      // 获取所有关键项目
      const keyItems = this.inputForm.quaItems.filter(item => item.isKeyItem === 1);

      if (keyItems.length === 0) {
        // 如果没有关键项目，所有项目都合格则通过
        const allQualified = this.inputForm.quaItems.every(item => item.isQualified);
        this.inputForm.overallResult = allQualified ? '1' : '0';
      } else {
        // 有关键项目，关键项目都合格则通过
        const allKeyItemsQualified = keyItems.every(item => item.isQualified);
        this.inputForm.overallResult = allKeyItemsQualified ? '1' : '0';
      }
      this.updateInputHasChanges();
    },
    updateInputHasChanges() {
      const changedItems = this.inputForm.quaItems.filter(r => {
        const base = this.inputOriginalMap[r.quaItemId] || { testResult: null, isQualified: null };
        return String(r.testResult ?? '') !== String(base.testResult ?? '') || Boolean(r.isQualified) !== Boolean(base.isQualified);
      });
      this.inputHasChanges = changedItems.length > 0;
    },
    cancelInputDialog() {
      if (this.inputHasChanges) {
        this.$confirm('存在未保存的修改，确定要关闭吗？', '提示', { type: 'warning' })
          .then(() => { this.inputDialog = false; })
          .catch(() => {});
      } else {
        this.inputDialog = false;
      }
    },
    onCloseInputDialog(done) {
      if (this.inputHasChanges) {
        this.$confirm('存在未保存的修改，确定要关闭吗？', '提示', { type: 'warning' })
          .then(() => { done(); })
          .catch(() => {});
      } else {
        done();
      }
    },
    handleFileSuccess(response, file, fileList, row) {
      row.fileList = fileList;
      // 若后端返回文件URL，尝试写入附件结果中，并标记为变更
      try {
        if (response && response.url) {
          row.testResult = row.testResult ? (row.testResult + ',' + response.url) : response.url;
          this.validateResult(row);
        }
      } catch (e) {}
    },
    handleFileRemove(file, fileList, row) {
      row.fileList = fileList;
    },
    // 动物淘汰相关
    handleEliminate() {
      this.currentAction = 'eliminate';
      this.openAnimalSelectDialog();
    },
    confirmEliminate() {
      this.$modal.confirm('是否确认淘汰选中的动物？').then(() => {
        const promises = this.selectedAnimalIds.map(id => eliminateAnimal(id));
        Promise.all(promises).then(() => {
          this.$modal.msgSuccess("动物淘汰成功");
          this.eliminateDialog = false;
          this.getList();
        });
      }).catch(() => {});
    },
    // 分配笼位相关
    handleAssignCage() {
      this.currentAction = 'assign';
      this.openAnimalSelectDialog();
    },
    openAnimalSelectDialog() {
      this.animalSelectDialog = true;
      this.selectedAnimalIds = [];
      this.animalSelectList = [];
      this.animalSelectTotal = 0;
      this.animalSelectQueryParams.pageNum = 1;
      this.getAnimalSelectList();
    },
    handleAnimalSelectQuery() {
      this.animalSelectQueryParams.pageNum = 1;
      this.getAnimalSelectList();
    },
    resetAnimalSelectQuery() {
      this.resetForm("animalSelectQueryForm");
      this.handleAnimalSelectQuery();
    },
    getAnimalSelectList() {
      listAnimal(this.animalSelectQueryParams).then(response => {
        this.animalSelectList = response.rows;
        this.animalSelectTotal = response.total;
      });
    },
    handleAnimalSelectChange(selection) {
      this.selectedAnimalIds = selection.map(item => item.animalId);
      if (this.currentAction === 'assign' && selection.length > 1) {
        // 单选限制：保留最后一个
        const last = selection[selection.length - 1];
        this.selectedAnimalIds = [last.animalId];
      }
    },
    confirmAnimalSelect() {
      if (!this.selectedAnimalIds.length) {
        this.$modal.msgError("请先选择动物");
        return;
      }
      if (this.currentAction === 'eliminate') {
        this.animalSelectDialog = false;
        this.eliminateDialog = true;
      } else if (this.currentAction === 'assign') {
        const animalId = this.selectedAnimalIds[0];
        const selected = this.animalSelectList.find(a => a.animalId === animalId);
        if (selected) {
          this.cageForm.animalCode = selected.animalId;
          this.cageForm.animalName = selected.userName || selected.animalName || '';
        }
        this.animalSelectDialog = false;
        this.assignCageDialog = true;
        this.availableCages = [];
        this.getAvailableCages();
      }
    },
    getAvailableCages() {
      this.loading = true;
      listCage({ pageSize: 1000 }).then(response => {
        this.availableCages = response.rows;
        this.loading = false;
      });
    },
    confirmAssignCage() {
      this.$refs["cageForm"].validate(valid => {
        if (valid) {
          const data = {
            animalId: this.selectedAnimalIds[0],
            cageId: this.cageForm.cageId,
            position: this.cageForm.position,
            remark: this.cageForm.remark
          };

          assignCage(data).then(response => {
            this.$modal.msgSuccess("分配成功");
            this.assignCageDialog = false;
            this.getList();
          });
        }
      });
    },
  }
};
</script>
